import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { verifyToken } from '@/app/lib/auth';
import prisma from '@/app/lib/prisma';

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    // 获取用户的饮食记录
    const records = await prisma.dietRecord.findMany({
      where: { userId: payload.userId },
      orderBy: { date: 'desc' },
    });

    // 获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: payload.userId },
    });

    // 计算统计数据
    const totalRecords = records.length;
    const uniqueDays = new Set(records.map(r => r.date.toISOString().split('T')[0])).size;
    const averageCalories = records.reduce((sum, r) => sum + r.calories, 0) / totalRecords || 0;

    const stats = {
      totalRecords,
      daysTracked: uniqueDays,
      averageCalories,
      latestWeight: user?.weight || null,
    };

    return NextResponse.json({ stats });
  } catch (error) {
    console.error('获取用户统计数据错误:', error);
    return NextResponse.json(
      { message: '获取用户统计数据失败' },
      { status: 500 }
    );
  }
} 